package xin.marcher.module.rights.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.redis.RedisCache;
import xin.marcher.module.rights.domain.bo.EshopUserDetails;
import xin.marcher.module.rights.domain.dto.LoginResultDTO;
import xin.marcher.module.rights.domain.request.CheckTokenRequest;
import xin.marcher.module.rights.domain.request.LoginRequest;
import xin.marcher.module.rights.repository.LoginRepository;
import xin.marcher.module.rights.service.LoginService;

import java.util.Objects;
import java.util.Set;
import java.util.UUID;

/**
 *
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private LoginRepository loginRepository;

    @Autowired
    private RedisCache redisCache;

    @Override
    public LoginResultDTO login(LoginRequest request) {
        // 校验用户名和密码
        Authentication in = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
        Authentication out = authenticationManager.authenticate(in);

        // 用户及权限信息保存到redis
        EshopUserDetails userDetails = (EshopUserDetails) out.getPrincipal();
        String userDetailsKey = UUID.randomUUID().toString();

        // 保存用户登录信息
        loginRepository.saveUserDetails(userDetailsKey, userDetails);

        // 用jwt包装userDetailsKey
        String token = loginRepository.generateToken(userDetailsKey);
        return new LoginResultDTO(token, userDetails.getUserId());
    }

    @Override
    public JsonResult checkToken(CheckTokenRequest request) {

        if (StringUtils.isBlank(request.getToken())) {
            return JsonResult.buildError("");
        }

        // 解析token里的内容
        String userDeatilKey = loginRepository.parseToekn(request.getToken());

        // 获取用户登录信息和权限信息
        String jsonStr = redisCache.get(userDeatilKey);

        // 用户登录信息不存在
        EshopUserDetails eshopUserDetails = JSON.parseObject(jsonStr, EshopUserDetails.class);
        if (Objects.isNull(eshopUserDetails)) {
            return JsonResult.buildError("");
        }

        // 刷新一下缓存的过期时间
        loginRepository.renewLoginInfo(userDeatilKey);

        // admin账号有所有权限
        if (StringUtils.equals("admin", eshopUserDetails.getUsername())) {
            return JsonResult.buildSuccess(eshopUserDetails.toLoginUser());
        }

        // 没有没有任何权限
        Set<String> permissionCodes = eshopUserDetails.getPermissionCodes();
        if (Objects.isNull(permissionCodes)) {
            return JsonResult.buildError("");
        }

        // 用户没有指定的这个权限
        if (!permissionCodes.contains(request.getPermissionCode())) {
            return JsonResult.buildError("");
        }

        return JsonResult.buildSuccess(eshopUserDetails.toLoginUser());
    }

}
